package android.slc.popup.impl;

import android.slc.popup.SlcPopup2;
import android.widget.PopupWindow;

import androidx.appcompat.widget.ListPopupWindow;

import java.lang.ref.WeakReference;

/**
 * @Description:
 * @Author: sunlunchang
 * @CreateDate: 2022/04/07 下午 5:54
 */
public class PopupOperateImpl extends BaseOperateImpl<ListPopupWindow> implements SlcPopup2.PopupOperate {
    private ListPopupWindow mListPopupWindow;
    private final OnOperateDismissListener mOnOperateDismissListener;
    private PopupWindow.OnDismissListener mOnDismissListener;

    public PopupOperateImpl() {
        super();
        this.mOnOperateDismissListener = new OnOperateDismissListener(this);
    }


    @Override
    public SlcPopup2.PopupOperate setOnDismissListener(PopupWindow.OnDismissListener onDismissListener) {
        this.mOnDismissListener = onDismissListener;
        return this;
    }

    @Override
    public ListPopupWindow getListPopupWindow() {
        return mListPopupWindow;
    }

    @Override
    public void dismiss() {
        mListPopupWindow.dismiss();
    }

    @Override
    public void show(ListPopupWindow listPopupWindow) {
        if (SlcPopup2.existOperateByKey(getKey())) {
            return;
        }
        this.mOnOperateDismissListener.setKey(getKey());
        this.mOnOperateDismissListener.setOnDismissListener(this.mOnDismissListener);
        this.mListPopupWindow = listPopupWindow;
        //this.mListPopupWindow.setModal(isCancelable());
        this.mListPopupWindow.setOnDismissListener(this.mOnOperateDismissListener);
        //this.mListPopupWindow.postShow();
        this.mListPopupWindow.show();
        SlcPopup2.addOperate(getKey(), this);
    }

    private static class OnOperateDismissListener implements PopupWindow.OnDismissListener {
        private PopupOperateImpl baseOperate;
        private WeakReference<PopupWindow.OnDismissListener> onDismissListenerWeakReference;
        private String key;

        private OnOperateDismissListener(PopupOperateImpl baseOperate) {
            this.baseOperate = baseOperate;
        }

        private void setOnDismissListener(PopupWindow.OnDismissListener onDismissListener) {
            this.onDismissListenerWeakReference = new WeakReference<>(onDismissListener);
        }

        public void setKey(String key) {
            this.key = key;
        }

        @Override
        public void onDismiss() {
            PopupWindow.OnDismissListener onDismissListener = this.onDismissListenerWeakReference.get();
            this.baseOperate.mListPopupWindow = null;
            this.baseOperate = null;
            SlcPopup2.removeOperate(this.key);
            if (onDismissListener != null) {
                onDismissListener.onDismiss();
            }
        }
    }

}
